<!-- src/views/UserList.vue -->
<template>
  <div class="user-list">
    <div class="header">
      <h2>用户列表</h2>
      <el-button type="primary" @click="logout" size="small">退出登录</el-button>
    </div>
    <el-table :data="users" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
    </el-table>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'UserList',
  data() {
    return {
      users: [],
      loading: true
    }
  },
  created() {
    this.fetchUsers()
  },
  methods: {
    fetchUsers() {
      this.loading = true
      // 确保请求携带cookie
      request.get('/api/users', { withCredentials: true })
          .then(res => {
            console.log('用户列表响应:', res)

            if (res.success) {
              // 后端返回的是 {success: true, data: [...]} 格式
              this.users = Array.isArray(res.data) ? res.data : []
            } else {
              this.$message.error(res.message || '获取用户列表失败')
              if (res.message === '未登录') {
                this.logout()
              }
            }
          })
          .catch(err => {
            console.error('获取用户列表错误:', err)
            this.$message.error('加载失败: ' + (err.message || '未知错误'))
          })
          .finally(() => {
            this.loading = false
          })
    },
    logout() {
      // 调用后端登出接口（如果有的话）
      request.post('/api/logout', {}, { withCredentials: true })
          .finally(() => {
            // 清除本地存储
            localStorage.removeItem('user')
            localStorage.removeItem('token')
            // 跳转到登录页
            this.$router.push('/login')
          })
    }
  }
}
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>
